/**
 * 返回非负数字x中从右开始p位置的n个比特
 */

#include <stdio.h>

unsigned setbits(unsigned x, int p, int n, unsigned y);

int main() {
    unsigned x = 255;
    unsigned y = 1;
    int p = 7;
    int n = 2;
    printf("0x%x\n", setbits(x, p, n, y));

    return 0;
}

unsigned setbits(unsigned x, int p, int n, unsigned y) {
    return (x & ~(((1 << n) - 1) << (p - n + 1))) | ((y & ((1 << n) - 1)) << (p - n + 1));
}
